const Router = require('koa-router');
const fs = require('fs');

function getFileList(path) {
  return new Promise((resolve, reject) => {
    fs.readdir(path, function (err, res) {
      if (err) {
        console.log(err)
        reject();
        throw err;
      }
      resolve(res)
    })
  })
}

module.exports = async (router) => {
  const fileList = await getFileList('./controller');
  fileList.forEach(item => {
    if (item.includes('.js')) {
      const controllerRouter = new Router();
      const template = require('../controller/' + item);
      if (template.hide !== true) {
        for (let key in template) {
          const fn = template[key];
          let routerPath = key;
          if (['home', 'index'].includes(key)) {
            routerPath = ''
          }
          controllerRouter[fn.method && fn.method || 'get']('/' + routerPath, fn);
        }
        router.use('/' + (template.name || item.replace('.js', '')), controllerRouter.routes(), controllerRouter.allowedMethods())
      }
    }
  })
  router.all('*', async (ctx, next) => {
    ctx.status = 404
    next()
  })
}
